import redis
import json

from django.conf import settings


class MyRedis:
    def __init__(self, host='localhost', port=6379, db=1, password=None):
        self.redis_pool = redis.ConnectionPool(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            db=settings.REDIS_DB,
            password=settings.REDIS_PASSWORD,
            decode_responses=True
        )
        self.__conn = redis.Redis(connection_pool=self.redis_pool)

    def setex(self, key, ex, value):   # 过期时间
        """设置key-value，并设置过期时间"""
        return self.__conn.setex(key, ex, value)

    def setnx(self, key, value):   # 分布式锁
        return self.__conn.setnx(key, value)

    def set(self, key, value):
        return self.__conn.set(key, value)

    def get(self, key):
        return self.__conn.get(key)


    def delete(self, key):
        """删除key"""
        return self.__conn.delete(key)

    def exists(self, key):
        """检查key是否存在"""
        return self.__conn.exists(key)

    def list_lrange(self, key, start, end):
        """从list中获取指定范围的元素"""
        return self.__conn.lrange(key, start, end)

    def list_del(self, key, value):
        """从list中删除指定值的元素"""
        return self.__conn.lrem(key, 0, value)

    def set_str(self, key, value):
        """设置字符串值"""
        return self.__conn.set(key, value)

    def list_push(self, key, value):
        """向list中添加元素"""
        return self.__conn.lpush(key, value)

    def expire(self, key, seconds):
        """设置key的过期时间"""
        return self.__conn.expire(key, seconds)

    # list列表的方法
    # 左进右出
    def lpush(self, key, value):   # 左进
        self.__conn.lpush(key, value)

    def rpush(self, key, value):
        self.__conn.rpush(key, value)

    def rpop(self, key):  # 右出
        return self.__conn.rpop(key)

    def llen(self, key):
        return self.__conn.llen(key)

    def lrange(self, key, start, end):
        return self.__conn.lrange(key, start, end)

    def rpushlpop(self, list1, list2):
        return self.__conn.rpoplpush(list1, list2)

    def ldelete(self, key, count=0, value=None):
        return self.__conn.lrem(key, count, value)

    def lrem(self, key, count, value):
        return self.__conn.lrem(key, count, value)


mredis = MyRedis()
